﻿using System;
using System.Linq;
using System.Collections.Generic;

namespace Com.ContentRendering.Api.LoaderEngine
{
    /// <summary/>
    internal class SectionReaders
    {
        /// <summary/>
        internal class NamedSectionReader
        {
            private string _name;
            private SectionReader _sectionReader;

            /// <summary/>
            internal NamedSectionReader(
                string name,
                SectionReader sectionReader)
            {
                this._name = name;
                this._sectionReader = sectionReader;
            }

            /// <summary/>
            internal string Name
            {
                get { return this._name; }
            }

            /// <summary/>
            internal SectionReader SectionReader
            {
                get { return this._sectionReader; }
            }
        }

        private Stack<NamedSectionReader> _namedSectionReaders;

        /// <summary/>
        internal SectionReaders()
        {
            this._namedSectionReaders = new Stack<NamedSectionReader>();
        }

        /// <summary/>
        internal void Add(
            string name,
            SectionReader sectionReader)
        {
            this._namedSectionReaders.Push(new NamedSectionReader(name,sectionReader));
        }

        /// <summary/>
        internal bool ContainsName(string name)
        {
            return this._namedSectionReaders.Count(value => value.Name == name) != 0;
        }

        /// <summary/>
        internal bool MoveNext()
        {
            while(this._namedSectionReaders.Count != 0)
            {
                SectionReader sectionReader = this._namedSectionReaders.Peek().SectionReader;

                // if nothing then remove and try next
                if (sectionReader.MoveNext())
                {
                    return true;
                }

                // remove from stack
                this._namedSectionReaders.Pop();
            }

            return false;
        }

        /// <summary/>
        internal string Section
        {
            get { return this._namedSectionReaders.Peek().SectionReader.Section; }
        }
    }
}
